package com.kedacom.demo.modularity.feed;

import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.cxf.jaxrs.provider.json.JSONProvider;

import com.kedacom.demo.modularity.core.BusinessExceptionMapper;
import com.kedacom.demo.modularity.core.ResponseExceptionMapper;
import com.kedacom.demo.modularity.email.EmailService;
import com.kedacom.demo.modularity.message.XMPPMessageGateway;

public class FeedServerRunnable implements Runnable {

	private String url;
	private String emailServiceUrl;
	private String xmppGatewayUrl;

	public FeedServerRunnable(String url, String emailServiceUrl, String xmppGatewayUrl) {
		super();
		this.url = url;
		this.emailServiceUrl = emailServiceUrl;
		this.xmppGatewayUrl = xmppGatewayUrl;
	}

	@Override
	public void run() {
		List<Object> responseProviders = new ArrayList<Object>();
		responseProviders.add(new JSONProvider<Object>());
		responseProviders.add(new ResponseExceptionMapper());

		EmailService emailService = JAXRSClientFactory.create(emailServiceUrl, EmailService.class, responseProviders);
		XMPPMessageGateway xmppMessageGateway = JAXRSClientFactory.create(xmppGatewayUrl, XMPPMessageGateway.class,
				responseProviders);

		FeedServiceImpl feedService = new FeedServiceImpl();
		feedService.setEmailService(emailService);
		feedService.setXmppMessageGateway(xmppMessageGateway);

		JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
		sf.setResourceClasses(FeedService.class);
		sf.setResourceProvider(FeedService.class, new SingletonResourceProvider(feedService));
		List<Object> providers = new ArrayList<Object>();
		providers.add(new JSONProvider<Object>());
		providers.add(new BusinessExceptionMapper());
		sf.setProviders(providers);
		sf.setAddress(url);
		sf.create();
	}

}
